package com.chen.solution.rpc.account.svc.repository;

import cn.hutool.core.util.IdUtil;
import com.chen.solution.rpc.account.svc.model.Account;
import org.springframework.stereotype.Repository;

import java.time.Instant;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @author ChenTian
 * @date 2022/4/12
 */
@Repository
public class AccountRepository {

    /**
     * 模拟用户信息持久化
      */
    private Map<String, Account> accountMap = new ConcurrentHashMap<>();

    /**
     * 模拟创建用户
     */
    public Account createAccount(String name, String email, String phoneNumber) {
        Account account = Account.builder()
                .id(IdUtil.getSnowflakeNextIdStr())
                .name(name)
                .email(email)
                .phoneNumber(phoneNumber)
                .memberSince(Instant.now())
                .build();
        accountMap.put(account.getId(), account);
        return account;
    }

    /**
     * 模拟获取用户
     */
    public Account getAccountByUserId(String userId) {
        return accountMap.get(userId);
    }

    /**
     * 模拟获取用户
     */
    public Account getAccountByName(String name) {
        Optional<Account> account = accountMap.values().stream().filter(c -> name.equals(c.getName())).findFirst();

        return account.orElse(null);
    }

    public Account getByPhoneNumber(String phoneNumber){
        Optional<Account> account = accountMap.values().stream().filter(c -> phoneNumber.equals(c.getPhoneNumber())).findFirst();

        return account.orElse(null);
    }
    /**
     * 模拟获取用户列表
     */
    public List<Account> getAccounts(int offset, int limit) {
        return accountMap.values().stream()
                .sorted(Comparator.comparing(Account::getId))
                .skip(offset)
                .limit(limit)
                .collect(Collectors.toList());
    }

    /**
     * 模拟更新用户
     */
    public void update(Account newAccount) {
        Account account = getAccountByUserId(newAccount.getId());
        if(account == null){
            return;
        }

        accountMap.put(newAccount.getId(), newAccount);
    }

    public void deleteAll() {
        accountMap = new HashMap<>();
    }
}
